package cn.controller;

import cn.entity.AuthenticationRequest;
import cn.entity.UserDto;
import cn.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/7/26 22:07
 */
@RestController
public class LoginController {

    @Autowired
    private AuthenticationService authenticationService;

    /**
     * 用户登录
     *
     * @param authenticationRequest 登录请求
     * @return
     */
    @PostMapping(value = "/login", produces = {"application/json;charset=UTF-8"})
    //@PostMapping(value = "/login")
    public String login(AuthenticationRequest authenticationRequest, HttpSession session) {
        UserDto userDto = authenticationService.authertication(authenticationRequest);
        System.out.println(userDto);
        // 将用户信息放入session
        session.setAttribute(UserDto.SESSION_USER_KEY, userDto);
        return userDto.getFullname() + " success!";
    }

    /**
     * 注销登录
     *
     * @param session
     * @return
     */
    @GetMapping(value = "/logout", produces = "application/json;charset=UTF-8")
    public String logout(HttpSession session) {
        session.invalidate();
        return "退出成功";
    }

    /**
     * 测试资源1
     *
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r1", produces = "application/json;charset=UTF-8")
    public String r1(HttpSession session) {
        String fullname = null;
        Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (userObj != null) {
            fullname = ((UserDto) userObj).getFullname();
        } else {
            fullname = "匿名";
        }
        return fullname + " 访问资源1";
    }

    /**
     * 测试资源2
     *
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r2",  produces = "application/json;charset=UTF-8")
    public String r2(HttpSession session) {
        String fullname = null;
        Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (userObj != null) {
            fullname = ((UserDto) userObj).getFullname();
        } else {
            fullname = "匿名";
        }
        return fullname + " 访问资源2";
    }
}
